//
//  DUCalSelectedTextField.swift
//  SimpleCal
//
//  Created by 杜晓祥 on 2021/12/15.
//

import Cocoa

@IBDesignable
class DUCalSelectedTextField: NSTextField {
    
    private var iconLayer: CALayer!
    private var calpop:DUCalSelectedView!
    private var calMenu = NSMenu(title: "cal")
    
    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        initialize()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        initialize()
    }
    
    override func layout() {
        if self.layer?.sublayers == nil {
            self.layer?.addSublayer(iconLayer)
        }
    }
    
    private func initialize () {
        self.isEditable = false
        calpop = DUCalSelectedView()
        iconLayer = CALayer()
        iconLayer.frame = getFrame()
        let img = NSImage(named: "dateIcon")
        calpop.confirmHandler = confirmHandler
        iconLayer.contents = img
        createMenu(view: calpop)
        
        calpop.updateData = {(h: Int, w: Int, f: Int) in
            self.stringValue = "假期\(h)天,加班\(w)天,节日/事件:\(f)天"
        }
    }
    
    private func createMenu (view: NSView) {
        let menuItem = NSMenuItem.init()
        menuItem.view = view
        calMenu.addItem(menuItem)
        
    }
    
    private func getFrame () -> NSRect {
        let s = getSize()
        let r = NSMakeRect(self.frame.width - s.width - 2, 2, s.width, s.height)
        return r
    }
    
    private func getSize() -> CGSize {
        let size = CGSize(width: self.frame.size.height - 4, height: self.frame.size.height - 4)
        return size
    }
    
    override func mouseDown(with event: NSEvent) {
        let d = CalendarUtil.getNowDate()
        calpop.setDate(year: d.year, month: d.month)
        calpop.multCalInHidden = false
        calMenu.popUp(positioning: calMenu.item(at: 0), at: NSPoint(x: 0, y: self.frame.height + 5), in: self)
    }
    
    private func confirmHandler(_ sender: [BaseViewButton.StateValue: [DateEntity]]) {
        print(sender)
        calMenu.cancelTracking()
    }
    
}
